/*
MIT License
Copyright (c) 2008 Humberto Roa

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

/**
 * @constructor
 */
var simpleTopoSort = {};

/**
 * purpose: Array to hold sort.
 * @private
 * @type Array
 */
simpleTopoSort._sortedItemArray = [];

/**
 * purpose: Add an item to the sort. The item will be placed after the dependencies. 
 * Dependencies will be automatically added to the sort as nedded.
 * @param String Name The name of the item. Example: "A"
 * @param Array Dependencies An array of dependency names. Example: ["B", "C"]
 * @return Void
 */
simpleTopoSort.addItem = function(/*String*/ Name, /*Array*/ Dependencies){
	var dependencyPosition = null;
	
	// add depencencies to _sortedItemArray as needed
	for (var i=0; i < Dependencies.length; i++) {
		dependencyPosition = this._getItemIndex(Dependencies[i]);
		if(dependencyPosition == -1){
			this._sortedItemArray.unshift(Dependencies[i]); // add dependency to top
		}
	}
	
	// check if Name is in this._sortedItemArray
	// if not, add it after the dependency with the largest index
	var namePosition = this._getItemIndex(Name);
	if(namePosition === -1){
		// find the maximum dependency index
		var maxDependency = 0;
		for (var i=0; i < Dependencies.length; i++) {
			dependencyPosition = this._getItemIndex(Dependencies[i]);
			maxDependency = (dependencyPosition > maxDependency) ? dependencyPosition: maxDependency;
		}
		
		this._sortedItemArray.splice(maxDependency + 1, 0, Name);
	} else if(namePosition < maxDependency){
		// error
		this._log('Circular reference error when trying to add: ' + Name);
	}
	
	this._log('Add Item Result: ' + this._sortedItemArray);
};

/**
 * purpose: Get the sorted items in an array.
 * @return Array Example: ["C", "B", "A"]
 */
simpleTopoSort.getSortedItems = function(){
	return this._sortedItemArray;
};

/**
 * purpose: Resets the sort by removing all the existing items. 
 * @return Void
 */
simpleTopoSort.reset = function(){
	this._sortedItemArray = [];
}

/**
 * purpose: Remove an item from the sorted array. Useful for updating the sort based on 
 * external events. 
 * @return Void
 */
simpleTopoSort.removeItem = function(/*String*/ Name){
	var index = this._getItemIndex(Name);
	if( index >= 0){
		// remove Name from this._sortedItemArray
		this._sortedItemArray.splice(index, 1);
	}
}

/**
 * purpose: Get the index of a Name in the sorted array.
 * @private
 * @return Integer The index of the Name. Returns -1 if the Name is not in the sort.
 */
simpleTopoSort._getItemIndex = function(/*String*/ Name){
	if(this._sortedItemArray.length > 0){
		// loop through array to find Name
		// if found, return index
		// if not found, return -1
		for (var i = 0; i < this._sortedItemArray.length; i++) {
			if (this._sortedItemArray[i] === Name) {
				// return Name index in this._sortedItemArray
				return i;
			} 
		}
		
		// Name is not in this._sortedItemArray
		return -1;

	} else {
		// this._sortedItemArray is empty
		return -1;
	}
}

/**
 * purpose: Wrapper for Firebug console.log().
 * @private
 */
simpleTopoSort._log = function(Data){
	if(console.log) console.log(Data);
}

/*
// sample usage
window.loadFirebugConsole();

simpleTopoSort.reset();
simpleTopoSort.addItem('E', ['C']);
simpleTopoSort.addItem('D', ['B', 'C']);
simpleTopoSort.addItem('C', ['B']);
simpleTopoSort.addItem('B', ['A']);
console.info('Final Array: ' + simpleTopoSort.getSortedItems());
//Final Array: A,B,C,D,E

simpleTopoSort.removeItem('B');
console.info('Final Array: ' + simpleTopoSort.getSortedItems());
//Final Array: A,C,D,E

// wikipedia example
// http://en.wikipedia.org/wiki/Topological_sort
simpleTopoSort.reset();
simpleTopoSort.addItem('2',  ['11']);
simpleTopoSort.addItem('9',  ['11', '8']);
simpleTopoSort.addItem('10', ['11', '3']);
simpleTopoSort.addItem('11', ['7', '5']);
simpleTopoSort.addItem('8',  ['7', '3']);
console.info('Final Array: ' + simpleTopoSort.getSortedItems());
//Final Array: 5,7,3,8,11,10,9,2
*/
